<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h3>管理员信息</h3>
          <p>查看和管理您的个人信息</p>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="profile-tabs">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="info">
          <div class="info-section">
            <h4>个人信息</h4>
            <el-form
                :model="profileForm"
                label-width="100px"
                class="profile-form"
            >
              <el-form-item label="ID">
                <el-input v-model="profileForm.id" disabled />
              </el-form-item>

              <el-form-item label="用户名">
                <el-input v-model="profileForm.username" disabled />
              </el-form-item>

              <el-form-item label="手机号">
                <el-input v-model="profileForm.phone" disabled />
              </el-form-item>

              <el-form-item label="邮箱">
                <el-input v-model="profileForm.email" disabled />
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 修改密码标签页 -->
        <el-tab-pane label="修改密码" name="password">
          <div class="password-section">
            <h4>修改密码</h4>
            <el-form
                :model="passwordForm"
                ref="passwordFormRef"
                label-width="100px"
                class="password-form"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input
                    v-model="passwordForm.oldPassword"
                    type="password"
                    show-password
                    placeholder="请输入原密码"
                />
              </el-form-item>

              <el-form-item label="新密码" prop="newPassword">
                <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    show-password
                    placeholder="请输入新密码"
                />
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    show-password
                    placeholder="请再次输入新密码"
                />
              </el-form-item>

              <el-form-item>
                <el-button
                    type="primary"
                    @click="changePassword"
                    :loading="passwordLoading"
                    round
                >
                  修改密码
                </el-button>
                <el-button @click="resetPasswordForm" round>重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getJwtPayload } from '@/util/auth.js'
import manager_api from "@/api/manager/manager_api.js";

// 获取路由对象
const router = useRouter()

// 定义响应式数据
const activeTab = ref('info')
const passwordLoading = ref(false)

// 表单引用
const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 基本信息表单
const profileForm = reactive({
  id: '',
  username: '',
  phone: '',
  email: '',
})

/*// 基本信息表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '用户名长度应在3-16个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}*/

// 获取管理员信息
const getProfileInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    // 从JWT token解析payload获取基本信息
    const payload = getJwtPayload()

    if (payload) {
      // 注意：JWT payload中的字段名是字符串"ID"和"USERNAME"
      const idValue = payload["ID"]
      profileForm.id = idValue ? (typeof idValue === 'number' ? idValue : parseInt(idValue)) || '' : ''
      profileForm.username = payload["USERNAME"] || ''
    }

    // 如果能获取到ID，则尝试从后端获取详细信息
    const idValue = payload?.["ID"]
    const managerId = idValue ? (typeof idValue === 'number' ? idValue : parseInt(idValue)) : null

    if (managerId && !isNaN(managerId)) {
      const res = await manager_api.find(managerId)

      if (res && res.id) {
        profileForm.id = res.id
        profileForm.username = res.username
        profileForm.phone = res.phone || ''
        profileForm.email = res.email || ''
      } else if (res && res.code === 200 && res.data) {
        const data = res.data
        console.log('data', data)
        profileForm.id = data.id
        profileForm.username = data.username
        profileForm.phone = data.phone || ''
      } else {
        ElMessage.error(res?.msg || '获取详细信息失败')
      }
    }
  } catch (error) {
    console.error('获取管理员信息失败:', error)
    ElMessage.error('获取管理员信息失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return

  const valid = await passwordFormRef.value.validate()
  if (!valid) return

  passwordLoading.value = true

  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      passwordLoading.value = false
      return
    }

    // 使用manager_api调用修改密码接口
    const res = await manager_api.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    // 添加调试日志
    console.log('修改密码响应:', res)
    console.log('响应类型:', typeof res)
    console.log('响应code:', res?.code)
    console.log('code === 200:', res?.code === 200)

    if (res && res.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      resetPasswordForm()

      // 弹出确认框后跳转到登录页
      ElMessageBox.confirm('密码已修改，需要重新登录', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        showCancelButton: false
      }).then(() => {
        // 清除token并跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('userRole')
        router.push('/login')
      })
    } else {
      ElMessage.error(res?.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('密码修改失败: ' + (error.response?.data?.msg || error.message))
  } finally {
    passwordLoading.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''

  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 组件挂载时获取信息
onMounted(() => {
  getProfileInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  min-height: 100%;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(168, 192, 235, 0.2);
  border: none;
}

:deep(.profile-card .el-card__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  border-radius: 15px 15px 0 0 !important;
  padding: 25px;
  border: none;
}

.card-header h3 {
  margin: 0 0 8px 0;
  font-size: 22px;
  font-weight: 600;
  color: #409eff;
}

.card-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.profile-tabs {
  margin-top: 20px;
}

:deep(.el-tabs__item) {
  font-weight: 500;
  color: #666;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background: #409eff;
}

.info-section, .password-section {
  padding: 20px;
}

.info-section h4, .password-section h4 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.profile-form,
.password-form {
  max-width: 500px;
  margin: 0 auto;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }

  .profile-card {
    margin: 0 10px;
  }
}
</style>
